type Color = { r: number; g: number; b: number };

// 插值颜色
function interpolateColor(start: Color, end: Color, factor: number): Color {
  return {
    r: Math.round(start.r + (end.r - start.r) * factor),
    g: Math.round(start.g + (end.g - start.g) * factor),
    b: Math.round(start.b + (end.b - start.b) * factor),
  };
}

// 转换为十六进制颜色
function colorToHex(color: Color): string {
  const toHex = (value: number) => value.toString(16).padStart(2, "0");
  return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`;
}

// 生成平滑的二维插值因子矩阵
function generateSmoothFactors(rows: number, cols: number): number[][] {
  const factors: number[][] = [];
  for (let i = 0; i < rows; i++) {
    const rowFactor = i / (rows - 1); // 行因子
    const row: number[] = [];
    for (let j = 0; j < cols; j++) {
      const colFactor = j / (cols - 1); // 列因子
      const factor = (rowFactor + colFactor) / 2; // 行列平均因子
      row.push(factor);
    }
    factors.push(row);
  }
  return factors;
}

// 添加平滑的噪声
function addNoise(factors: number[][], noiseAmplitude: number): number[][] {
  return factors.map((row) =>
    row.map((factor) =>
      Math.min(1, Math.max(0, factor + (Math.random() - 0.5) * noiseAmplitude))
    )
  );
}

// 生成平滑的二维渐变颜色数组
export function generateSmoothGradientArray(
  rows: number,
  cols: number,
  noiseAmplitude: number = 0.1
): string[][] {
  const startColor: Color = { r: 255, g: 0, b: 0 }; // 红色
  const endColor: Color = { r: 0, g: 0, b: 255 }; // 蓝色

  // 生成平滑因子矩阵
  let factors = generateSmoothFactors(rows, cols);

  // 添加轻微随机噪声
  factors = addNoise(factors, noiseAmplitude);

  // 生成颜色矩阵
  const gradientArray: string[][] = [];
  for (let i = 0; i < rows; i++) {
    const row: string[] = [];
    for (let j = 0; j < cols; j++) {
      const factor = factors[i][j];
      const interpolatedColor = interpolateColor(startColor, endColor, factor);
      row.push(colorToHex(interpolatedColor));
    }
    gradientArray.push(row);
  }
  return gradientArray;
}
